package com.bailugansan.efficiencyboard.interceptor;

import com.bailugansan.efficiencyboard.annotation.UserLoginToken;
import com.bailugansan.efficiencyboard.service.impl.JwtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author BailuGansan
 */
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    JwtService jwtService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");

        HandlerMethod handlerMethod=(HandlerMethod)handler;
        Method method=handlerMethod.getMethod();

        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if (userLoginToken.required()) {
                // 执行认证
                if (token == null) {
                    throw new RuntimeException("无token，请重新登录");
                }

                System.out.println(token);
                // 解析 token
                Map<String, Object> tokenData = jwtService.parseToken(token);

                // 验证 token
                int code = jwtService.verifyToken(token);
                if(code != 0) {
                    throw new RuntimeException("401");
                }

                // 判断 token 是否有效
                if(jwtService.isEffective(tokenData, token)) {
                    return true;
                } else {
                    throw new RuntimeException("token已过期或token无效");
                }

            }
        }
        return true;
    }
}
